import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';

import '../../config/kq_core_global.dart';
import '../../resources/images.dart';
import '../button/kq_ink_well.dart';
import '../image/kq_image.dart';

/// 图片容器
class KqImageBox extends StatefulWidget {
  /// 列数，默认4
  final int cols;

  /// 最大图片容量，默认8
  final int maxQty;

  /// 图片之间的间距，默认10
  final double? spacing;

  /// 图片类型和路径
  final List<ImageUrl> urls;

  /// 能否编辑，不能编辑则不显示删除和添加按钮，默认true
  final bool editable;

  /// 删除按钮是否启用，默认开启
  final bool deleteEnable;

  /// 自定义添加按钮图片
  final String? customAddPic;

  /// 自定义添加按钮图片的颜色
  final Color? customAddPicColor;

  /// 自定义添加按钮图片的Package
  final String? customAddPicPackage;

  /// 图片缩放类型
  final BoxFit? fit;

  /// 图片数量变化回调
  final Function()? onChanged;

  /// 图片添加按钮点击回调
  final Function(List<ImageUrl> urls, KqImageBoxState state)? onAddTap;

  /// 图片删除按钮点击回调
  final Function(List<ImageUrl> urls, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onDeleteTap;

  /// 图片点击回调
  final Function(List<ImageUrl> urls, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onImageTap;

  const KqImageBox({Key? key,
    required this.urls,
    this.onAddTap,
    this.onDeleteTap,
    this.onImageTap,
    this.spacing,
    this.cols = 4,
    this.maxQty = 8,
    this.fit,
    this.customAddPic,
    this.customAddPicColor,
    this.customAddPicPackage,
    this.deleteEnable = true,
    this.editable = true,
    this.onChanged})
      : super(key: key);

  @override
  KqImageBoxState createState() => KqImageBoxState();
}

class KqImageBoxState extends State<KqImageBox> {
  /// 刷新
  void update() {
    setState(() {});
    if (widget.onChanged != null) {
      widget.onChanged!();
    }
  }

  /// 图片数量
  int count() {
    return widget.urls.length;
  }

  /// 添加图片
  void addImage(ImageUrl imageUrl) {
    if (widget.maxQty != 0 && widget.urls.length >= widget.maxQty) {
      return;
    }
    widget.urls.add(imageUrl);
    update();
  }

  /// 拼接提交的url
  String? getSubmitUrls({join = ','}) {
    if (widget.urls.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.urls) {
      values.add(url.url);
    }
    return values.isEmpty ? null : values.join(join);
  }

  /// 拼接提交的valueForSubmit
  String? getSubmitValues({join = ','}) {
    if (widget.urls.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.urls) {
      if (url.valueForSubmit != null) {
        values.add(url.valueForSubmit);
      }
    }
    return values.isEmpty ? null : values.join(join);
  }

  /// 删除图片
  void remove(ImageUrl imageUrl) {
    widget.urls.remove(imageUrl);
    update();
  }

  List<Widget> _buildImages() {
    var imageCount = 0;
    List<Widget> list = [];
    imageCount = widget.urls.length;
    for (int i = 0; i < imageCount; i++) {
      ImageUrl imageUrl = widget.urls[i];
      list.add(_buildImageItem(imageUrl, i));
    }
    if (imageCount < widget.maxQty && widget.editable) {
      list.add(
        _buildImageItem(
            ImageUrl(
              imageType: ImageType.assets,
              url: widget.customAddPic ?? Images.commonPicUpload88,
              uploadOk: true,
              isAddBtn: true,
              package: widget.customAddPicPackage ?? KqCoreGlobal.packageName,
            ),
            imageCount),
      );
    }
    return list;
  }

  /// 删除按钮
  Widget _buildDeleteButton() {
    return KqImage.assets(
      url: Images.commonIcShanchuJiaobiao,
      fit: BoxFit.fill,
      width: imageSize / 3,
      height: imageSize / 3,
      package: KqCoreGlobal.packageName,
    );
  }

  /// 图片或新增按钮
  Widget _buildImageItem(ImageUrl imageUrl, int position) {
    return KqInkWell(
        onTap: () {
          if (imageUrl.isAddBtn) {
            if (widget.onAddTap != null) {
              widget.onAddTap!(widget.urls, this);
            }
          } else {
            if (widget.onImageTap != null) {
              widget.onImageTap!(widget.urls, imageUrl, position, this);
            }
          }
        },
        child: Stack(
          children: [
            _buildImage(imageUrl),

            /// 删除按钮
            Visibility(
                visible: widget.deleteEnable &&
                    !imageUrl.isAddBtn &&
                    widget.editable,
                child: Positioned(
                    right: 0,
                    top: 0,
                    width: imageSize / 3,
                    height: imageSize / 3,
                    child: KqInkWell(
                      onTap: () {
                        if (widget.onDeleteTap != null) {
                          widget.onDeleteTap!(
                              widget.urls, imageUrl, position, this);
                        }
                      },
                      child: _buildDeleteButton(),
                    )))
          ],
        ));
  }

  double widgetWidth = 0;

  /// 每张图片大小DD
  double imageSize = 0;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        var spacing = widget.spacing ?? 10.r;
        widgetWidth = constraints.maxWidth;
        imageSize = (widgetWidth - spacing * (widget.cols - 1)) / widget.cols;
        return GridView.count(
          crossAxisCount: widget.cols,
          shrinkWrap: true,
          padding: EdgeInsets.zero,
          physics: const NeverScrollableScrollPhysics(),
          mainAxisSpacing: spacing,
          crossAxisSpacing: spacing,
          //宽高比
          childAspectRatio: 1 / 1,
          children: _buildImages(),
        );
      },
    );
  }

  Widget _buildImage(ImageUrl imageUrl) {
    if (imageUrl.imageType == ImageType.oss) {
      return KqImage.oss(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: widget.fit ?? BoxFit.cover,
        package: imageUrl.package,
      );
    } else if (imageUrl.imageType == ImageType.http) {
      return KqImage.http(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: widget.fit ?? BoxFit.cover,
        package: imageUrl.package,
      );
    } else if (imageUrl.imageType == ImageType.file) {
      return KqImage.file(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: widget.fit ?? BoxFit.cover,
        package: imageUrl.package,
      );
    } else {
      return KqImage.assets(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: imageUrl.isAddBtn ? BoxFit.cover : widget.fit ?? BoxFit.cover,
        color: imageUrl.isAddBtn ? widget.customAddPicColor : null,
        package: imageUrl.package,
      );
    }
  }
}

/// 图片类型和路径实体类
class ImageUrl {
  /// 图片类型
  ImageType imageType;

  /// 图片路径或链接
  String url;

  /// 是否上传完成，如果[url]是后端给的ossKey，则应该设置[uploadOk]为true。
  bool uploadOk;

  /// 用于提交给后端的数据，如果是oss的话，就是ossKey
  String? valueForSubmit;

  /// 自定义数据，用于存放临时数据
  dynamic extra;

  /// 包名，如果应用组件库内的图片，需要使用[KqCoreGlobal.packageName]
  String? package;

  /// 占位图
  String? placeHolder;

  /// 是否新增按钮，组件内部使用，不用赋值
  bool isAddBtn;

  ImageUrl({required this.imageType,
    required this.url,
    this.uploadOk = false,
    this.valueForSubmit,
    this.extra,
    this.package,
    this.placeHolder,
    this.isAddBtn = false});
}
